﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace NMF.Expressions
{

    internal abstract class ObservableStaticMethodBase<TDelegate, TResult> : ObservableExpression<TResult>
        where TDelegate : class
    {
        public ObservableStaticMethodBase(MethodInfo method)
        {
            if (method == null) throw new ArgumentNullException("method");

            Function = ReflectionHelper.CreateDelegate(typeof(TDelegate), method) as TDelegate;

            this.ValueChanged += MyValueChanged;
        }

        public ObservableStaticMethodBase(TDelegate function)
        {
            Function = function;
            this.ValueChanged += MyValueChanged;
        }

        public TDelegate Function { get; private set; }

        private void MyValueChanged(object sender, ValueChangedEventArgs e)
        {
            var disposable = e.OldValue as IDisposable;
            if (disposable != null)
            {
                disposable.Dispose();
            }
        }

        protected void ArgumentChanged(object sender, ValueChangedEventArgs e)
        {
            if (!IsAttached) return;
            Refresh();
        }

        public override ExpressionType NodeType
        {
            get
            {
                return ExpressionType.Invoke;
            }
        }
    }
}
